package dev.alm.javaproject.controller;

import com.sun.org.apache.xpath.internal.operations.Mult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
//@CrossOrigin
@Slf4j
public class FileUploadController {

    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) throws IOException {
        // 获取部署后的实际路径，并加上upload，作为上传文件的存储路径
        String realPath = request.getServletContext().getRealPath("/upload/");
        log.info("[log] 文件存储路径：" + realPath);
        saveFile(file, realPath);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", "200");
        map.put("message", "上传成功");
        map.put("data", realPath);
        return map;
    }

    private void saveFile(MultipartFile file, String path) throws IOException {
        // 判断目录是否存在，如不存在则创建
        File dir = new File(path);
        if (!dir.exists()) {
            // 目录不存在
            dir.mkdir();
        }
        File f = new File(path + file.getOriginalFilename());
        file.transferTo(f);
    }

}
